package com.kchouse.homepage;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.OfferItem;
import com.kchouse.bean.quoteDetail;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class OfferDetailsActivity extends BaseActivity implements View.OnClickListener {

    private OfferDetailsActivity mContent;
    private Intent intent;
    private TextView tv_title;
    private ImageView iv_back;
    private ListView lv_item1;
    private LvAdapter adapter1;
    private ListView lv_item2;
    private LvAdapter2 adapter2;
    private String id;
    private TextView tv_userMobile;
    private TextView tv_carNumber;
    private TextView tv_totalHours;
    private TextView tv_totalParts;
    private TextView tv_dealParts;
    private TextView tv_dealHours;
    private TextView tv_quoteTime;
    private TextView tv_totalAll;
    private double toatlall;//报价总计
    private double dealall;//成交总计
    private TextView tv_dealAll;
    private ArrayList<quoteDetail> list = new ArrayList<>();
    private ArrayList<quoteDetail> list1 = new ArrayList<>();
    private ArrayList<quoteDetail> list2 = new ArrayList<>();
    private Double totalHours;//当前工时总金额
    private Double totalParts;//当前配件总金额
    private TextView tv_ok;
    private String quoteId;
    private String status;//是否可以修改

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offer_details);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("报价详情");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        tv_ok = (TextView) findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(this);


        tv_userMobile = (TextView) findViewById(R.id.tv_userMobile);
        tv_carNumber = (TextView) findViewById(R.id.tv_carNumber);
        tv_totalHours = (TextView) findViewById(R.id.tv_totalHours);
        tv_totalParts = (TextView) findViewById(R.id.tv_totalParts);
        tv_dealParts = (TextView) findViewById(R.id.tv_dealParts);
        tv_dealHours = (TextView) findViewById(R.id.tv_dealHours);
        tv_quoteTime = (TextView) findViewById(R.id.tv_quoteTime);
        tv_totalAll = (TextView) findViewById(R.id.tv_totalAll);
        tv_dealAll = (TextView) findViewById(R.id.tv_dealAll);


        lv_item1 = (ListView) findViewById(R.id.lv_item1);
        lv_item2 = (ListView) findViewById(R.id.lv_item2);
        adapter1 = new LvAdapter();
        lv_item1.setAdapter(adapter1);
        adapter2 = new LvAdapter2();
        lv_item2.setAdapter(adapter2);
    }

    private void intiData() {
        intent = getIntent();
        id = intent.getStringExtra("id");
        GetOfferdetails(id);
    }

    /**
     * 获取报价详情
     */
    private void GetOfferdetails(String id) {
        String url = API.GetOfferdetails + id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("id", id);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    JSONObject datajson = JSONObject.parseObject(json.getString("data"));
                    JSONObject quotejson = JSONObject.parseObject(datajson.getString("quote"));
                    status = quotejson.getString("status");
                    if (status.equals("YES")) {
                        tv_ok.setVisibility(View.GONE);
                    } else {
                        tv_ok.setVisibility(View.VISIBLE);
                    }
                    quoteId = quotejson.getString("quoteId");
                    String userMobile = quotejson.getString("userMobile");
                    tv_userMobile.setText("手机号：" + userMobile);
                    String carNumber = quotejson.getString("carNumber");
                    tv_carNumber.setText("车牌号：" + carNumber);
                    totalHours = quotejson.getDouble("totalHours");
                    tv_totalHours.setText("工时小计：" + totalHours + "元");
                    totalParts = quotejson.getDouble("totalParts");
                    tv_totalParts.setText("配件小计：" + totalParts + "元");
//                    double dealParts = quotejson.getDouble("dealParts");
                    tv_dealParts.setText("配件成交：" + totalParts + "元");
//                    double dealHours = quotejson.getDouble("dealHours");
                    tv_dealHours.setText("工时成交：" + totalHours + "元");
                    String quoteTime = quotejson.getString("quoteTime");
                    tv_quoteTime.setText("报价时间：" + quoteTime.substring(0, 10).toString());
                    toatlall = totalHours + totalParts;
                    tv_totalAll.setText("报价总计：" + toatlall + "元");
//                    dealall = dealParts + dealHours;
                    tv_dealAll.setText("成交总计：" + toatlall + "元");

                    list.addAll(JSONObject.parseArray(quotejson.getString("quoteDetailList"), quoteDetail.class));
                    for (int i = 0; i < list.size(); i++) {
                        quoteDetail item = list.get(i);
                        if (item.getType().equals("HOURS")) {
                            list1.add(item);
                        } else {
                            list2.add(item);
                        }
                    }
                    adapter1.notifyDataSetChanged();
                    adapter2.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_ok:
                PostonfirmQuote();
                break;
        }
    }

    /**
     * 确认报价
     */
    private void PostonfirmQuote() {
        list.clear();
        String url = API.PostConfirmQuote;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        JSONObject ob = new JSONObject();
        ArrayList<HashMap> list = new ArrayList();
        for (int i = 0; i < list1.size(); i++) {
            quoteDetail item = list1.get(i);
            HashMap<String, String> hs = new HashMap<>();
            hs.put("quoteDetailId", item.getId());
            hs.put("status", item.getStatus());
            list.add(hs);
        }
        for (int j = 0; j < list2.size(); j++) {
            quoteDetail item = list2.get(j);
            HashMap<String, String> hs = new HashMap<>();
            hs.put("quoteDetailId", item.getId());
            hs.put("status", item.getStatus());
            list.add(hs);
        }
        ob.put("quoteDetails", list);
        ob.put("quoteId", quoteId);
        params.applicationJson(ob);
        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
//                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast("已确认成功");
                    finish();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if(data.getString("code").equals("401")||data.getString("code").equals("400"))
//                    {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    }else {
//                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }


    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list1.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            quoteDetail item = list1.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_manageline_item, null);
            TextView tv_detail = (TextView) view.findViewById(R.id.tv_detail);
            tv_detail.setText(item.getDetail());
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
            tv_price.setText(item.getPrice() + "");
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            tv_num.setText(item.getNum() + "");
            TextView tv_total = (TextView) view.findViewById(R.id.tv_total);
            double toatl = item.getPrice() * item.getNum();
            tv_total.setText(toatl + "");

            TextView tv_item = (TextView) view.findViewById(R.id.tv_item);


//            if(status.equals("NO")){
//                Log.e("+++","again");
            tv_item.setOnClickListener(new Lv1OnClick(item, tv_item, item.getStatus()));
//            }else {
            if (item.getStatus().equals("NO")) {
                tv_item.setBackground(null);
            } else {
                tv_item.setBackground(getResources().getDrawable(R.mipmap.ic_payright));
            }
//            }
            return view;
        }
    }

    class Lv1OnClick implements View.OnClickListener {

        private TextView tv_item;
        private quoteDetail item;
        private boolean istrue = true;

        //
        public Lv1OnClick(quoteDetail item, TextView tv_item, String status) {
            this.item = item;
            this.tv_item = tv_item;
            if (status.equals("YES")) {
                this.istrue = true;
            } else {
                this.istrue = false;
            }
        }

        @Override
        public void onClick(View v) {

            if (istrue) {
                istrue = false;
                tv_item.setBackground(null);
                totalHours = totalHours - (item.getPrice() * item.getNum());
                tv_dealHours.setText("工时成交：" + totalHours + "元");
                item.setStatus("NO");
            } else {
                istrue = true;
                tv_item.setBackground(getResources().getDrawable(R.mipmap.ic_payright));
                totalHours = totalHours + (item.getPrice() * item.getNum());
                tv_dealHours.setText("工时成交：" + totalHours + "元");
                item.setStatus("YES");
            }

            toatlall = totalHours + totalParts;
            tv_dealAll.setText("成交总计：" + toatlall + "元");

            Log.e("+++", item.getStatus());
            Log.e("+++", item.toString());
            Log.e("+++", list1.toString());
        }
    }

    class Lv2OnClick implements View.OnClickListener {

        private TextView tv_item;
        private quoteDetail item;
        private boolean istrue = true;

        public Lv2OnClick(quoteDetail item, TextView tv_item, String status) {
            this.item = item;
            this.tv_item = tv_item;
            if (status.equals("YES")) {
                this.istrue = true;
            } else {
                this.istrue = false;
            }
        }

        @Override
        public void onClick(View v) {

            if (istrue) {
                istrue = false;
                tv_item.setBackground(null);
                totalParts = totalParts - (item.getPrice() * item.getNum());
                tv_dealParts.setText("配件成交：" + totalParts + "元");
                item.setStatus("NO");
            } else {
                istrue = true;
                tv_item.setBackground(getResources().getDrawable(R.mipmap.ic_payright));
                totalParts = totalParts + (item.getPrice() * item.getNum());
                tv_dealParts.setText("配件成交：" + totalParts + "元");
                item.setStatus("YES");
            }

            toatlall = totalHours + totalParts;
            tv_dealAll.setText("成交总计：" + toatlall + "元");
        }
    }


    class LvAdapter2 extends BaseAdapter {
        @Override
        public int getCount() {
            return list2.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            quoteDetail item = list2.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_manageline_item, null);
            TextView tv_detail = (TextView) view.findViewById(R.id.tv_detail);
            tv_detail.setText(item.getDetail());
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
            tv_price.setText(item.getPrice() + "");
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            tv_num.setText(item.getNum() + "");
            TextView tv_total = (TextView) view.findViewById(R.id.tv_total);
            double toatl = item.getPrice() * item.getNum();
            tv_total.setText(toatl + "");
            TextView tv_item = (TextView) view.findViewById(R.id.tv_item);
//            if (status.equals("NO")) {
//                item.setStatus("YES");
            tv_item.setOnClickListener(new Lv2OnClick(item, tv_item, item.getStatus()));
//            } else {
            if (item.getStatus().equals("NO")) {
                tv_item.setBackground(null);
            } else {
                tv_item.setBackground(getResources().getDrawable(R.mipmap.ic_payright));
            }
//            }
            return view;
        }
    }
}
